#include "xfreeplugin.h"

XFreePlugin::XFreePlugin(){
    qDebug() << "In function "+QString(Q_FUNC_INFO);    
    QString seed = this->toString();
    ID = QCryptographicHash::hash( seed.toAscii(), QCryptographicHash::Md5);

    downloader = new Downloader(this);
    checked = true;

    connect(downloader, SIGNAL(errorOccured(const QString &)),
            this, SLOT(catchError(const QString&)));

    //>>>>>>>>
    //! connecting the downloader.done() signal to member slot finished()
    connect(downloader, SIGNAL(done(const QStringList&)),
            this, SLOT(finished(const QStringList&)));
    //<<<<<<<<

    QStringList latin_list = QStringList( QStringList() << "á" << "ä" << "é"
                                          << "í" << "ó" << "ö" << "ő" << "ú"
                                          << "ü" << "ű" << "ß"
                                          );

    QStringList hex_list = QStringList( QStringList() << "%E1" << "%E4" << "%E9"
                                        << "%ED" << "%F3" << "%F6" << "%F5"
                                        << "%FA" << "%FC" << "%FB" << "%DF"
                                        );

    /*
     *   Unfortunately some sites use deprecated percentage encoding
     *   so we have to code the search terms, before we pass them to the Downloader
     */
    latinToOldHex = utils::toStrPairList( latin_list, hex_list );


    searchKey=QString("mit");
    url.setHost("www.szotar.xfree.hu");
    url.setPath("/index.tvn");

    LangPairList lplst = ( LangPairList()
                           << qMakePair(ENG, HUN) << qMakePair(HUN, ENG)
                           << qMakePair(GER, HUN) << qMakePair(HUN, GER)
                           << qMakePair(FRA, HUN) << qMakePair(HUN, FRA)
                           << qMakePair(LAT, HUN) << qMakePair(HUN, LAT)
                           << qMakePair(ITA, HUN) << qMakePair(HUN, ITA)
                           );

    int i=0;
    foreach( LangPair pair, lplst ) {
        //!populating LangHash        
        supportedLangs[pair] = lngConv.lang2Str(pair.first) +"-"+ lngConv.lang2Str(pair.second);
        StrPairList lst;
        lst << StringPair( "nyelv" , QString().setNum(i) ) << StringPair( "pontossag" , "3" )
                << StringPair( "szotar_keres" , "Kereses" );
        query.insert( pair, lst );
        ++i;
    }


}

bool XFreePlugin::search(const State &s) {

       if (query.contains(s.dict)) {

        //unfortunately szotar.Xfree.hu uses deprecated percentage encoding
        //so we have to code the search terms, before we pass them to the Downloader
        QString word = utils::replace( s.word, latinToOldHex );


        StrPairList actQuery = query[s.dict];

        dir=(actQuery[1].second.toInt() % 2) == 1;
        switch (s.mode) {
        case 0:
            actQuery[1].second="3";
            break;
        case 1:
            actQuery[1].second="1";
            break;
        case 2:
            actQuery[1].second="2";
            break;
        case 3:
            actQuery[1].second="4";
            break;

        default:
            actQuery[1].second="4";
            break;
        }

        actQuery.prepend( qMakePair( searchKey, word ) );
        qDebug() <<"ACTQUERY: "<< actQuery;

        url.setQueryItems( actQuery );
        url.setScheme("http");
        qDebug()<<"DICTIONARIES_URL: "<<url.toString();
        downloader->setUrl(url);
        downloader->download();

        return true;

    } else {
        return false;
    }
}

void XFreePlugin::finished(const QStringList &lst ) {
    qDebug() << "In function "+QString(Q_FUNC_INFO);

    //*	&lst is a QStringList of downloaded html sites, but we only downloaded one site, so we need lst.first()
    QString result = lst.first();

    StrPairList rep;
    rep << qMakePair(QString("`"),QString("'"));

    result = utils::replace(result,rep);
    QRegExp first("<font color=\"#133572\">([^<]+[^\\s])\\s{0,1}</font>");
    QRegExp second("<font color=\"#133572\">\\s{0,1}<b>(.+[^\\s])\\s{0,1}</b>\\s{0,1}</font>");
    first.setMinimal(true);
    second.setMinimal(true);

    Parser parser( result, first, second );

    if ( dir ) parser.setRegExp(second, first);
    hash=parser.parse("\\");
    //utils::debug(pairList);
    qDebug()<<"##! In function "+QString(Q_FUNC_INFO)+": Emitting done( hash,url.host() )";
    emit done( hash,url.host() );
}

const LangHash XFreePlugin::getLangHash() const{
    return supportedLangs;
}

bool XFreePlugin::isChecked(){
    return checked;
}

QString XFreePlugin::description(){
    QStringList values=supportedLangs.values();
    return values.join(", ");//+tr("\nA Magyar-Olasz szótár hibás HTML miatt nem támogatott.");
}

void XFreePlugin::setChecked(bool opt){
    checked = opt;
}

void XFreePlugin::catchError(const QString &msg ){
    emit errorOccured( msg );
}

Q_EXPORT_PLUGIN2(xfreeplugin, XFreePlugin)
